﻿
// Our default grid options
var defaultGridOptions = {
    enableCellNavigation: true,
    enableColumnReorder: false,
    enableAddRow: false,
    editable: true,
    editOnDoubleClick: true,
    multiSelect: false,
    forceFitColumns: false,
    autoHeight: false,
    resizable: false,
    autoEdit: false,
    showHeaderRow: true,
    rowHeight: 36,
    headerHeight: 36,
    headerRowHeight: 36

};

$().ready(function () {
    $('.button').button();
    $('form').submit(function (event) {
        event.preventDefault();
    });
    var testsGrid = setUpStudyMaterialsGrid($('#studyMaterialsGrid'));
});

// Sets up the sample grid
function setUpStudyMaterialsGrid($gridSelector) {
    var columns = [
        { id: "Name", name: "Name", field: "Name", width: 400, sortable: true },
        {id: "buttons", name: "", field: "", width: 500, sortable: false, formatter: CellButtonFormatter, buttons: ["View", "Delete"] }
    ];

    // Set some additional options
    var options = $.extend(true, {}, defaultGridOptions);
    options.hasHeaderFilters = true;

    // Create the grid
    var grid = new Slick.Grid($gridSelector, [], columns, options);
    grid.registerPlugin(new Slick.ExtendedGrid($gridSelector, columns, options));

    grid.updateHeaderRow();

    // Make the grid buttons use jQuery UI
    grid.onRender.subscribe(function (e, args) {
        $('.slick-cell-button').button();
    });
    block({ element: $gridSelector, text: 'Loading' });
    $.getJSON('/StudyMaterialsManagement/ListMaterials', function (response) {
        if (response.Result)
            grid.dataView.setItems(response.Data);
        else {
            alert(response.Data);
        }
    });
    unblock({ element: $gridSelector });

    setUpAddMaterialDialog(grid);
    setUpDeleteMaterialDialog();
    $(document).on('click', $gridSelector.selector + ' .slick-cell-button-View', function () {
        var data = grid.getDataItem(grid.getActiveCell().row);
        window.open('/StudyMaterialsManagement/View/' + data.Id, data.Name);
    });
    //setUpViewMaterialDialog($gridSelector, grid);

    // Return the grid object so we can store it in a variable
    return grid;

    function setUpAddMaterialDialog(studyMaterialsGrid) {

        var _data;
        $('#fileupload').fileupload({
            dataType: 'json',
            done: function (e, data) {
            },
            add: function (e, data) {
                _data = data;
                $('#fileUploadFilename').text(data.files[0].fileName);
            }
        });
        $('#selectFileButton').click(function () {
            $('#fileupload').click();
        });
        var $dialog = $('#addStudyMaterialDialog');
        $dialog.dialog({
            modal: true,
            resizable: false,
            autoOpen: false,
            width: 450,
            height: 250,
            buttons:
                {
                    OK: function () {
                        var $this = $(this);
                        // Show a saving indicator
                        block({ element: $this, text: 'Saving' });
                        _data.submit().success(function(response) {
                            if (response.Result) {
                                // If the request succeeded, display the changes
                                grid.dataView.addItem(response.Data);
                                $('#addStudyMaterialForm').each(function () {
                                    this.reset();
                                });
                            } else {
                                // If it failed, show the error response
                                alert(response.Data);
                            }
                            $this.dialog('close');
                        }).error(function() {
                            // Let the user know an error occurred.
                            alert("An error occurred while saving your info. Please refresh the page and try again.");
                        }).complete(function() {
                            unblock({ element: $this });
                        });
                    },
                    Cancel:
                        function () {
                            // Clear the fields
                            //clearForm($('#addStudyMaterialForm'));
                            $('#addStudyMaterialForm').each(function () {
                                this.reset();
                            });
                            // Close the dialog box
                            $(this).dialog('close');
                        }
                }
        });

        $('#addStudyMaterialButton').click(function () {
            $dialog.dialog('open');
        });
    }

    function setUpDeleteMaterialDialog() {
        var $dialog = $('#deleteMaterialDialog');
        $dialog.dialog({
            modal: true,
            resizable: false,
            autoOpen: false,
            width: 400,
            buttons:
                {
                    OK: function () {
                        var $this = $(this);
                        // Show a saving indicator
                        block({ element: $this, text: 'Saving' });
                        var id = grid.getDataItem(grid.getActiveCell().row).Id;
                        // Post to the server
                        $.post('/StudyMaterialsManagement/Delete',
                        // Set up the data to transfer
                            {id: id },
                        // This function gets called if the server successfully returns a response. 
                        // This does not mean that no errors occurred; it means that no unhandled errors occurred.
                            function (response) {
                                if (response.Result) {
                                    // If the request succeeded, display the changes
                                    grid.dataView.deleteItem(id);
                                } else {
                                    // If it failed, show the error response
                                    alert(response.Data);
                                }
                                unblock({ element: $this });

                                // Close the dialog
                                $this.dialog('close');
                            }).error(function () {
                                // Remove the "saving" block
                                unblock({ element: $this });
                                // Let the user know an error occurred.
                                alert("An error occurred while saving your info. Please refresh the page and try again.");
                            });

                    },
                    Cancel:
                        function () {
                            // Close the dialog box
                            $(this).dialog('close');
                        }
                }
        });
        $(document).on('click', $gridSelector.selector + ' .slick-cell-button-Delete', function () {
            var row = grid.getDataItem(grid.getActiveCell().row);
            $('#studyMaterialName').text(row.Name);
            $dialog.dialog('open');
        });
    }
}
